目前元件部分,我們只學習到顯示靜態的資料,接下來我們會學習如何在元件中處理資料,並且顯示在畫面上。
目前 Anngular 支援兩種主要的變數儲存方式:
在剛開始時,我們先從傳統 TypeScript 變數開始,等到對基礎有一定的了解後,再來學習 Signals。
在 Angular 元件中,可以使用 JacaScript 類別的相關語法來定義變數,並且可以使用 TypeScript 的型別系統來定義變數的資料結構。
export class MyComponent {
// 基本變數
// 過於簡單的型別,其實可以省略不寫,交由 TypeScript 自動推斷,會比較適合。
title: string = 'Todo App';
count: number = 0;
isVisible: boolean = true;
// 陣列和物件
items: string[] = [];
user: { name: string; email: string } = { name: '', email: '' };
tasks: Array<{ id: number; title: string; completed: boolean }> = [];
}
可以將型別額外抽離成介面 (Interface)、或型別 (Type Alias),來定義更複雜的資料結構。
至於檔案檔案擺放的位置,則看團隊的習慣,以下是常見的做法:
src/app/models/user.model.ts
、src/app/types/task.type.ts
src/app/todo/todo.model.ts
interface IUser {
name: string;
email: string;
age?: number; // 可選屬性
}
type TTask = {
id: number;
title: string;
completed: boolean;
};
user: IUser = { name: '', email: '' };
tasks: TTask[] = [];
export class CTask {
constructor(
public id: number,
public title: string,
public completed = false,
) {}
toggle() {
this.completed = !this.completed;
}
}
tasks: CTask[] = [new Task(1, 'Learn Angular')]
字串插值是 Angular 中最常用的資料綁定方式之一,可以將元件中的資料顯示在 HTML 模板中。字串插值使用雙大括號 {{ }}
包裹要顯示的資料。
export class MyComponent {
title: string = 'Todo App';
}
{{ title }}
今日目標,建立專案樣式。
template.html
,可先嘗試依照模板著手建立 Todo List 的元件結構
目前我們學習了定義資料,以及了解如何在模板中顯示資料,接下來我們會學習如何將資料跟動態資料繫結。